import {login, logout, getInfo, smsCode, register} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'
import {trace} from "../../utils/trace"
import {getConfig, pwdreset, pwdtoken, SMSLogin} from "../../api/user"

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    sites: [],
    balance: 0,
    totalInAmount: 0,
    customAmount: 0,
    config: {},
    userInfo: {},
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_BALANCE: (state, balance) => {
    state.balance = Number(balance) * .01.toFixed(2)
  },
  SET_SITES: (state, sites) => {
    state.sites = sites
  },
  SET_TOTALINAMOUNT: (state, totalInAmount) => {
    state.totalInAmount = Number(totalInAmount) * .01.toFixed(2)
  },
  SET_CUSTOMAMOUNT: (state, customAmount) => {
    state.customAmount = Number(customAmount) * .01.toFixed(2)
  },

  SET_CONFIG: (state, config) => {
    state.config = config;
  }

}

const actions = {
  // user login
  login({commit}, userInfo) {
    const {username, password} = userInfo
    return new Promise((resolve, reject) => {
      login({key: username.trim(), password: password}).then(response => {
        const {data} = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  SMSLogin({commit}, userInfo) {
    const {phone, smsCode} = userInfo
    return new Promise((resolve, reject) => {
      SMSLogin({code: smsCode, phone: phone}).then(response => {
        const {data} = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
//找回密码（获得token）
  pwdtoken({commit}, obj) {
    const {phone, code} = obj
    return new Promise((resolve, reject) => {
      pwdtoken(obj).then(response => {
        const {data} = response
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
//找回密码（重置密码）
  pwdreset({commit}, obj) {
    const {token, password} = obj
    return new Promise((resolve, reject) => {
      pwdreset(obj).then(response => {
        const {data} = response
        // commit('SET_TOKEN', data.token)
        // setToken(data.token)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  register({commit}, data) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      register(data).then(response => {
        const {data} = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  //

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {data} = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const {account, avatar, mainSite, next1Site, next2Site, mainId, next1Id, next2Id, balance, WXInAmount, ALInAmount,consumeAmount,consumeAmount2} = data

        trace("user=", data, account)

        commit('SET_INFO', data)
        commit('SET_NAME', account)
        commit('SET_AVATAR', avatar)
        commit('SET_BALANCE', balance)
        commit('SET_TOTALINAMOUNT', WXInAmount + ALInAmount)
        commit('SET_CUSTOMAMOUNT', consumeAmount)
        let sites = [];
        if (mainSite.length > 5) sites.push({link: mainSite, id: mainId, tag: "官网", level: 1});
        if (next1Site.length > 5) sites.push({link: next1Site, id: next1Id, tag: "子站点", level: 2});
        if (next2Site.length > 5) sites.push({link: next2Site, id: next2Id, tag: "子站点", level: 3});
        trace("userinfo =", sites, balance)
        commit('SET_SITES', sites)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  /**
   * 发送短信验证码
   * @param commit
   * @param state
   * @returns {Promise<any>}
   */
  smsCode({commit}, phone) {
    return new Promise((resolve, reject) => {
      smsCode(phone).then(response => {
        const {data} = response
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      try {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      } catch (e) {
        reject(e)
      }
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resolve()
    })
  },

  // 配置信息-查询
  getConfig({commit}) {
    return new Promise((resolve, reject) => {
      getConfig().then((data) => {
        commit('SET_CONFIG', data.data)
        resolve(data.data);
      })
        .catch(err => {
          reject(err)
        })

    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

